<template>
  <a-form
    ref="formRef"
    :model="formState"
    :rules="rules"
    :label-col="labelCol"
    :wrapper-col="wrapperCol"
  >
    <a-form-item label="机构名称" name="departName">
      <a-input v-model:value="formState.departName" placeholder="请输入机构/部门名称" />
    </a-form-item>
    <a-form-item label="上级部门" name="parentId">
      <a-tree-select
        v-model:value="formState.parentId"
        show-search
        style="width: 100%"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
        placeholder=""
        allow-clear
        tree-default-expand-all
        :tree-data="treeData"
        tree-node-filter-prop="label"
        :fieldNames="{children:'children', label:'departName', value: 'id' }"
        disabled
      >
        <!-- <template #title="{ value: val, label }">
          <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
          <template v-else>{{ label }}</template>
        </template> -->
      </a-tree-select>
    </a-form-item>
    <a-form-item label="机构编码" name="orgCode">
      <a-input v-model:value="formState.orgCode" placeholder="请输入机构编码" disabled />
    </a-form-item>
    <a-form-item label="机构类型" name="orgCategory">
      <a-radio-group v-model:value="formState.orgCategory" button-style="solid">
        <a-radio-button v-for="item in categoryOptions" 
        :key="item.value" :value="item.value">{{item.label}}</a-radio-button>
      </a-radio-group>
    </a-form-item>    
    <a-form-item label="上传文件">
     <div :class="`${prefixCls}-container`">
      <okUploadTable :fileList="value" v-bind="bindProps" :update="handleUpdate" :theme="appTheme" :formatUploadData="formatUploadData" :customRemovePromise="customRemovePromise" :customDisplayList="customDisplayList"></okUploadTable>
    </div>
    </a-form-item>
    <a-form-item label="排序" name="departOrder">
      <a-input-number v-model:value="formState.departOrder" />
    </a-form-item>
    <a-form-item label="电话" name="mobile">
      <a-input v-model:value="formState.mobile" placeholder="请输入电话" />
    </a-form-item>
    <a-form-item label="传真" name="fax">
      <a-input v-model:value="formState.fax" placeholder="请输入传真" />
    </a-form-item>
    <a-form-item label="地址" name="address">
      <a-input v-model:value="formState.address" placeholder="请输入地址" />
    </a-form-item>
    <a-form-item label="备注" name="memo">
      <a-textarea v-model:value="formState.memo" placeholder="请输入备注" />
    </a-form-item>
    <!-- <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
      <a-button type="primary" @click="onSubmit">Create</a-button>
      <a-button style="margin-left: 10px" @click="resetForm">Reset</a-button>
    </a-form-item> -->
  </a-form>
</template>
<script lang="ts" setup>
import { Dayjs } from 'dayjs';
import { reactive, ref, toRaw } from 'vue';
// import type { UnwrapRef } from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import { values } from 'xe-utils';

//上传文件-stasrt
import {  computed, inject, unref } from 'vue';
import { propTypes } from '/@/utils/propTypes';
import { useAttrs } from '/@/hooks/core/useAttrs';
import { useDesign } from '/@/hooks/web/useDesign';
import { UploadTypeEnum } from '/@/components/Form/src/cyj/components/JUpload/upload.data';
import { uploadFileUrl } from '/@/api/common/api';
import { okUploadTable } from '@byteluck/ok-wc-ui';
import { useFile } from '/@/components/Form/src/cyj//hooks/useFile';


  const appTheme = inject('appTheme');
  const { prefixCls } = useDesign('j-upload');
  const attrs = useAttrs();
  const emit = defineEmits(['change', 'update:value']);
  const props = defineProps({
    value: propTypes.oneOfType([propTypes.string, propTypes.array]),
    text: propTypes.string.def('上传'),
    fileType: propTypes.string.def(UploadTypeEnum.all),
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: propTypes.string.def(''),
    /**
     * 是否返回url，
     * true：仅返回url
     * false：返回fileName filePath fileSize
     */
    // returnUrl: propTypes.bool.def(true),
    // 最大上传数量
    maxCount: propTypes.number.def(0),
    // buttonVisible: propTypes.bool.def(true),
    multiple: propTypes.bool.def(true),
    // 是否显示左右移动按钮
    // mover: propTypes.bool.def(true),
    // 是否显示下载按钮
    download: propTypes.bool.def(true),
    // 删除时是否显示确认框
    // removeConfirm: propTypes.bool.def(false),
    beforeUpload: propTypes.func,
    disabled: propTypes.bool.def(false),
    // 替换前一个文件，用于超出最大数量依然允许上传
    // replaceLastOne: propTypes.bool.def(false),
  });

  // 当前是否是上传图片模式
  const isImageMode = computed(() => props.fileType === UploadTypeEnum.image);

  const { formatUploadData, handleUpdate, customRemovePromise, customDisplayList, generateDir } = useFile(emit, 'file');

  // 合并 props 和 attrs
  const bindProps = computed(() => {
    //update-begin-author:liusq date:20220411 for: [issue/455]上传组件传入accept限制上传文件类型无效
    const bind: any = Object.assign({}, props, unref(attrs));
    //update-end-author:liusq date:20220411 for: [issue/455]上传组件传入accept限制上传文件类型无效

    bind.action = uploadFileUrl;
    bind.name = 'file';
    bind.listType = isImageMode.value ? 'picture-card' : 'text';
    bind.class = [bind.class, { 'upload-disabled': props.disabled }];
    bind.data = {dir: generateDir()}

    // 如果当前是图片上传模式，就只能上传图片
    if (isImageMode.value && !bind.accept) {
      bind.accept = 'image/*';
    }

    let operation = ['preview', 'download', 'remove'];
    if (!bind.download) {
      operation = ['preview', 'remove'];
    }
    bind.operation = operation;
    return bind;
  });


//上传文件-end

// 部门树列表数据
const treeData = ref<any[]>([]);
const formRef = ref();
const labelCol = { style: { width: '120px' } };
const wrapperCol = { span: 18 };
const fomrData = {
  departName: '',
  parentId: undefined,
  orgCode: undefined,
  orgCategory: undefined,
  departOrder: undefined,
  mobile: undefined,
  fax: undefined,
  address: undefined,
  memo: undefined,
}
let formState = ref( fomrData );
let categoryOptions = ref<any[]>([]);

const rules: Record<string, Rule[]> = {
  departName: [
    { required: true, message: '机构名称不能为空', trigger: 'blur' },
  ],
};

const updateCategoryOptions = (data) => {
  categoryOptions.value = data || [];
};

const updateTreeData = (data) => {
  treeData.value = data || [];
};

const onSubmit = async () => {
 return await formRef.value.validate()
    // .then(() => {
    //   console.log('values', formState, toRaw(formState));
    //   return values
    // })
    // .catch(error => {
    //   console.log('error', error);
    // });
};

const resetForm = (data) => {
  formRef.value.resetFields();
  formState.value = {...fomrData, ...data};
  // console.log(data);
};

// 定义暴露接口
export interface Exposed {
  resetForm,
  onSubmit,
  updateCategoryOptions,
  updateTreeData
}

// 暴露方法给父组件
defineExpose<Exposed>({
  resetForm,
  onSubmit,
  updateCategoryOptions,
  updateTreeData
})

</script>

<style lang="less" scoped>
</style>
